from flask import current_app, jsonify, render_template, g, request
from sqlalchemy.testing import in_

from info import constants, db
from info.models import News, User, Comment, CommentLike
from info.modules.news import news_blue
from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blue.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    user = g.user

    try:
        news_id_data = News.query.filter(News.id == news_id).one()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify("网络出错，请稍后再试试！！！")
    # 校验当前id数据库里是否存在
    if not news_id_data:
        # 不存在返回当前新闻不存在¬
        return jsonify("新闻编号不存在，请检查后再请求！！！")
    news_id_data.clicks += 1

    # 存在新闻详情内容
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    is_collect = False
    if user:
        if news_id_data in user.collection_news:
            is_collect = True

    comment_data = []
    # 获取新闻评论列表
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="评论数据查询失败")

    # 返回是否点击字段
    comment_cl_list = []
    if user:
        comm_list = [comment.id for comment in comments]
        try:
            comment_cl = CommentLike.query.filter(CommentLike.comment_id.in_(comm_list),
                                                  CommentLike.user_id == user.id).all()
            for con in comment_cl:
                comment_cl_list.append(con.comment_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="是否点赞数据查询失败")

    for item in comments:
        comment = item.to_dict()
        comment["is_like"] = False
        if user and item.id in comment_cl_list:
            comment["is_like"] = True
        comment_data.append(comment)

    # 返回作者信息
    is_follow = None
    news_user = None
    if news_id_data.user_id:
        try:
            news_user = User.query.filter(User.id == news_id_data.user_id).first()

        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="作者信息查询失败")
        # 返回当前用户有无关注该新闻
        # 1、查询当前用户所关注的所有新闻
        try:
            followers = news_user.followers.filter(User.id == user.id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询关注的用户失败,请稍后再试")

        # 校验一下fllowers是否存在
        if followers:
            print("followers存在", followers)
            is_follow = True
        else:
            print("followers不存在", followers)
            is_follow = False

    # 2、判断一下当前的新闻是否在该用户的关注列表里
    data = {
        'news': news_id_data.to_dict(),
        'user_info': user.to_dict() if user else None,
        'click_news_list': news_list,
        'is_collect': is_collect,
        'comment_data': comment_data,
        'news_user': news_user.to_dict() if news_user else None,
        'is_follow': is_follow
    }

    return render_template("news/detail.html", data=data)


@news_blue.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    print("进入收藏函数")
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1、获取数据
    json_data = request.json
    news_id = json_data.get("news_id")
    action = json_data.get("action")
    # 2、校验数据
    if not all([news_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg="数据缺失")

    if not action in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DATAERR, errmsg="数据传入错误")

    # 校验当前传入的新闻id是否在数据库里存在
    try:
        news_data = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not news_data:
        return jsonify(errno=RET.DATAERR, errmsg="当前新闻不存在")

    # 查询当前用户所收藏的新闻
    # try:
    #     user_collection = user.collection_news.all()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    # print("user_collection", user_collection)

    # 3、添加数据库
    try:
        if action == "collect":
            user.collection_news.append(news_data)
        else:
            user.collection_news.remove(news_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据添加失败")
    # 4、返回数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据提交失败")

    return jsonify(errno=RET.OK, errmsg="成功")


@news_blue.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    """添加评论"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    json_data = request.json
    news_id = json_data.get("news_id")
    comment = json_data.get("comment_input")
    parent_id = json_data.get("parent_id")

    # 判断传入的数据是否均存在
    if not all([news_id, comment]):
        return jsonify(errno=RET.DATAERR, errmsg="数据传入错误")

    news_id = int(news_id)

    user = int(user.id)

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据传入错误")

    if not news:
        return jsonify(errno=RET.DATAERR, errmsg="无新闻数据")

    # 添加评论数据
    com = Comment()
    com.user_id = user
    com.news_id = news_id
    com.content = comment
    if parent_id:
        parent_id = int(parent_id)
        com.parent_id = parent_id
    try:
        db.session.add(com)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, data=com.to_dict())


@news_blue.route("/comment_like", methods=["post"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 1、获取数据
    da_json = request.json
    comment_id = da_json.get("comment_id")
    news_id = da_json.get("news_id")
    action = da_json.get("action")

    # 将数据强转为int数字类型
    try:
        comment_id = int(comment_id)
        news_id = int(news_id)
        userid = int(user.id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据强转数值失败")

    # 2、校验传入的数据是否均存在
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg="数据传入错误")

    # 3、校验传入的新闻id是否存在
    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")

    if not news:
        return jsonify(errno=RET.DATAERR, errmsg="新闻不存在,请确认后再试")

    # 4、校验当前评论是否存在
    try:
        comment = Comment.query.filter(Comment.id == comment_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if not comment:
        return jsonify(errno=RET.DATAERR, errmsg="评论不存在,请确认后再试")

    # 5、校验传入进来的action是不是add或remove
    if action not in ("add", "remove"):
        return jsonify(errno=RET.DATAERR, errmsg="action参数传入错误")

    # 向数据库添加记录
    if action == "add":

        # 校验当前点赞是否已经存在
        like = CommentLike.query.filter_by(comment_id=comment_id, user_id=userid).first()
        if not like:
            try:
                commentlike = CommentLike()
                commentlike.comment_id = comment_id
                commentlike.user_id = user.id
                db.session.add(commentlike)
                comment.like_count += 1
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="数据库添加失败")
    else:
        try:
            like = CommentLike.query.filter_by(comment_id=comment_id, user_id=userid).first()
            if like:
                db.session.delete(like)
                comment.like_count -= 1
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库取消失败")

    # commit进数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库提交失败")

    return jsonify(errno=RET.OK, errmsg="成功")


@news_blue.route("/followed_user", methods=["POST"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="您还为登录,需要登录后才能关注哦")

    # 获取关注需要的参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    print(user_id)
    print(action)
    # 校验传入的参数是否有缺失
    if not all([user_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg="传入的参数缺失")

    # 校验action是否是关注或者是取消关注两选项
    if action not in ['follow', 'unfollow']:
        return jsonify(errno=RET.DATAERR, errmsg="传入的参数有误,请确认再试")

    # 校验一下当前被关注的人是否存在于数据库里
    try:
        news_user = User.query.filter(User.id == user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    if not news_user:
        return jsonify(errno=RET.DATAERR, errmsg="该用户暂未在本平台注册,暂时还无法关注哦")

    # 校验当前用户是否有关注
    try:
        user_follow_all = user.followed.filter(User.id == news_user.id).first()
        print("user_follow_all", user_follow_all)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    if action == "follow":
        if user_follow_all:
            print("当前用户暂未关注")
            return jsonify(errno=RET.DATAERR, errmsg="已经关注")
        user.followed.append(news_user)
    else:
        if user_follow_all:
            print("执行删除函数")
            user.followed.remove(news_user)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="成功")
